import Taro, { Component } from '@tarojs/taro';
import { View, Button, Text, ScrollView, Image, Label } from '@tarojs/components';
import classNames from 'classnames';
import { observer, inject } from '@tarojs/mobx';
import './index.styl';
import dayjs from 'dayjs';
import Article from '../../data-center/article';

class Index extends Component {
  constructor() {
    this.state = {
      activeIndex: 0,
      tabs: ['all', 'good', 'share', 'ask']
    };
  }

  config = {
    // enablePullDownRefresh: true //开启下拉刷新
  };

  componentWillMount() {
    Taro.getSystemInfo({
      success: res => {
        const { windowHeight } = res;

        this.winHeight = windowHeight;
      }
    });

    this.initData();
  }

  setStateAsync(data) {
    return new Promise(resolve => {
      this.setState(data, () => {
        resolve();
      });
    });
  }

  async initData() {
    const { tabs } = this.state;
    const topicObj = tabs.reduce((result, tab, index) => {
      result[tab] = {
        page: 1,
        list: []
      };
      return result;
    }, {});

    await this.setStateAsync({ ...topicObj });

    this.getData();
  }

  async getData(isRefresh = false) {
    const { activeIndex, tabs } = this.state;

    const key = tabs[activeIndex];

    if (this.state[key]) {
      const { page, list } = this.state[key];

      const params = {
        page,
        tab: key
      };

      const { data } = await Article.getTopic(params);

      if (data) {
        const result = data.map(article => {
          const {
            title,
            author,
            reply_count,
            visit_count,
            create_at,
            top,
            tab,
            id,
            good
          } = article;
          return {
            id,
            isTop: top,
            labal: this.getLabal(tab, top, good),
            title,
            img_url: author.avatar_url,
            author: author.loginname,
            commentNumber: reply_count,
            readNumber: visit_count,
            time: dayjs(create_at).format('YYYY-MM-DD HH:mm:ss'),
            lastRead: '9小时前'
          };
        });

        this.setState({
          [key]: {
            page: page + 1,
            list: list.concat(result)
          }
        });
      }
    }
  }

  getLabal(tabName, isTop, good) {
    if (isTop) {
      return '置顶';
    }

    if (good) {
      return '精品';
    }

    const types = ['ask', 'share', 'job', 'good'];

    return ['问答', '分享', '求职', '精选'][
      types.findIndex(a => a === tabName)
    ];
  }

  componentWillReact() {}

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  handleSelect(index) {
    this.setState({ activeIndex: index });
  }

  onScrollToLower(e) {
    console.log('Enter');
  }

  generateTabClass(index) {
    const { activeIndex } = this.state;
    return classNames({
      'index-tabs-dot': true,
      'index-tabs-dot__active': activeIndex === index
    });
  }

  swiperChange = e => {
    const { current } = e.detail;

    this.setState({ activeIndex: current }, () => {
      const { tabs } = this.state;

      const { list } = this.state[tabs[current]];

      if (!list.length) {
        this.getData();
      }
    });
  };

  onScrollToUpper() {
    console.log('onScrollToUpper');

    this.setState({ activeIndex : 2});
  }

  openArticleDetail(id) {
    Taro.navigateTo({
      url: '/pages/detail/index?' + `id=${id}`
    });
  }

  render() {
    const contentStyle = {
      height: this.winHeight + 'px'
    };

    const { activeIndex, tabs } = this.state;

    const Tabs = tabs.map((tab, index) => {
      const tabClass = this.generateTabClass(index);
      const tabName = ['全部', '精选', '分享', '问答'][index];
      return (
        <View
          className="index-tabs-item"
          taroKey={String(index)}
          onClick={this.handleSelect.bind(this, index)}
        >
          <View className={tabClass} />
          {tabName}
        </View>
      );
    });

    const SwiperItem = tabs.map(tab => {
      const tabKey = this.state[tab] && this.state[tab].list;
      const upperThreshold = -100;
      return (
        <SwiperItem className="index-content-swiper__item" taroKey={tab}>
          <ScrollView
            className="scrollView"
            scrollWithAnimation
            scrollY
            upperThreshold={upperThreshold}
            onScrollToUpper={this.getData.bind(this, true)}
            onScrollToLower={this.getData.bind(this)}
          >
            {tabKey.map((item, index) => {
              const { isTop, id } = item;
              const labalStyle = {
                background: isTop ? '#fee440' : null
              };
              return (
                <View
                  onClick={this.openArticleDetail.bind(this, id)}
                  taroKey={String(index)}
                  class="index-article"
                >
                  <View class="wrap">
                    <View className="index-article-title">
                      <View
                        className="index-article-title__labal"
                        style={labalStyle}
                      >
                        {item.labal}
                      </View>

                      <View className="index-article-title__content">
                        {item.title}
                      </View>
                    </View>

                    <View className="index-article-content">
                      <View className="index-article-left">
                        <Image
                          src={item.img_url}
                          className="index-article-image"
                        />
                      </View>

                      <View className="index-article-right">
                        <View class="index-article-right-content">
                          <View>{item.author}</View>

                          <View>
                            <Label className="yellow">{`${
                              item.commentNumber
                            } `}</Label>{' '}
                            / {item.readNumber}
                          </View>
                        </View>

                        <View class="index-article-right-content margin-top-4">
                          <View>{item.time}</View>
                          <View>{item.lastRead}</View>
                        </View>
                      </View>
                    </View>
                  </View>
                </View>
              );
            })}
          </ScrollView>
        </SwiperItem>
      );
    });

    return (
      <View className="index" style={contentStyle}>
        <View className="index-wrap">
          <View className="index-tabs">{Tabs}</View>
        </View>

        <View className="index-content">
          <Swiper
            current={activeIndex}
            onChange={this.swiperChange}
            className="index-content-swiper"
          >
            {SwiperItem}
          </Swiper>
        </View>
      </View>
    );
  }
}

export default Index;